package com.hwatsang.dao.impl;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import org.springframework.util.CollectionUtils;

import com.hwatsang.dao.UserDao;
import com.hwatsang.model.User;

public class HibernateUserDaoImpl extends HibernateDaoSupport implements UserDao {
	
	private static final Logger LOGGER = LoggerFactory.getLogger(HibernateUserDaoImpl.class);
		
	public String createUser(User user) {
		
		LOGGER.debug("Creating user [mobilePhone={}, name={}].", user.getMobilePhone(), user.getName()) ;
		
		return String.valueOf(getHibernateTemplate().save(user));		
	}

	public boolean updateUser(User user) {
		
		LOGGER.debug("Updating user with id {}.", user.getId());
		
		getHibernateTemplate().update(user);
		return true;
	}

	public boolean deleteUserById(String id) {
		
		LOGGER.debug("Deleting user with id {}.", id);
		
		User user = getUserById(id);
		if(user == null) {
			return false;
		} else {
			getHibernateTemplate().delete(user);
			return true;			
		}		
	}

	public User getUserById(String id) {
		
		LOGGER.debug("Getting user with id {}.", id);
		
		return getHibernateTemplate().get(User.class, Long.valueOf(id));		
	}
	
	@SuppressWarnings("unchecked")
	public User getUserByMobilePhone(String mobilePhone) {
//		List<User> users = getSession().createCriteria("User").add(Restrictions.eq("mobilePhone", mobilePhone)).list();
		List<User> users = getHibernateTemplate().find("from User where mobilePhone = " + mobilePhone);
		
		if(CollectionUtils.isEmpty(users)) {
			return null;
		} else {
			return users.get(0);
		}
	}

	@SuppressWarnings("unchecked")
	public List<User> listUsers() {
		return getHibernateTemplate().find("from User");		
	}
}
